package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.query.DestinationQuery;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DestinationServiceImpl implements IDestinationService {
    @Autowired
    private DestinationRepository destinationRepository;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private IRegionService regionService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Destination destination) {
        destinationRepository.save(destination);
    }

    @Override
    public void update(Destination destination) {
        destinationRepository.save(destination);
    }

    @Override
    public void delete(String id) {
        destinationRepository.deleteById(id);
    }

    @Override
    public Destination get(String id) {
        return destinationRepository.findById(id).orElse(null);
    }

    @Override
    public List<Destination> listAll() {
        return destinationRepository.findAll();
    }

    @Override
    public List<Destination> getDestByRegionId(String rid) {
        // 1、获取关联的目的地ids
        List<String> refIds = regionService.get(rid).getRefIds();
      /*  // 2、遍历获取所有的目的地
        List<Destination> list = new ArrayList<>();
        for (String id : refIds) {
            Destination destination = destinationService.get(id);
            list.add(destination);
        }*/

        // 2、通过目的地id集合 获取相应的目的地集合  where id in(...)
        List<Destination> destinations = destinationRepository.findByIdIn(refIds);
        return destinations;
    }

    @Override
    public Page<Destination> query(DestinationQuery qo) {
        // 方法1：
      /*  Query query = new Query();
        // keyword
        if (StringUtils.hasLength(qo.getKeyword())){
        query.addCriteria(Criteria.where("name").regex(qo.getKeyword()));
        }
        // toasts
        if (StringUtils.hasLength(qo.getParentId())) {
            query.addCriteria(Criteria.where("parentId").is(qo.getParentId()));
        }else {
            query.addCriteria(Criteria.where("parentId").is(null));
        }
        // total
        long total = mongoTemplate.count(query, Destination.class);
        if (total == 0) {
            return Page.empty();
        }
        // list
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        // 不要忘了这个
        query.with(pageable);
        List<Destination> destinations = mongoTemplate.find(query, Destination.class);
        return new PageImpl<>(destinations,pageable,total);*/

        // 方法2：抽取为工具类
        Query query = new Query();
        // keyword
        if (StringUtils.hasLength(qo.getKeyword())){
            query.addCriteria(Criteria.where("name").regex(qo.getKeyword()));
        }
        // toasts
        if (StringUtils.hasLength(qo.getParentId())) {
            query.addCriteria(Criteria.where("parentId").is(qo.getParentId()));
        }else {
            query.addCriteria(Criteria.where("parentId").is(null));
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(mongoTemplate,query,Destination.class,pageable);
    }

    @Override
    public List<Destination> getToasts(String parentId) {
        // 1、创建一个数组存放 目的地（吐司）
        List<Destination> list = new ArrayList<>();

        // 2、调用递归方法（将父亲的目的地放到list中）  或者
        // while(StringUtils.hasLength(parentId)){
        //         Destination destination = destinationRepository.findById(parentId).orElse(null);
        //        list.add(destination);
        //        parentId = destination.getParentId()；
        //    }
        this.createToasts(list,parentId);

        // 3、集合元素顺序颠倒
        Collections.reverse(list);
        return list;
    }

    private void createToasts(List<Destination> list,String parentId){
        // 1、判断它的老爸是否存在(parentId)
        if (!StringUtils.hasLength(parentId)) {
            return;
        }
        // 2、存在，将parentId作为id，找到老爸，加到list中
        Destination destination = destinationRepository.findById(parentId).orElse(null);
        list.add(destination);
        // 3、再判断这个老爸 的老爸的parentId是否存在，存在，再调用自己
        if (StringUtils.hasLength(destination.getParentId())){
            this.createToasts(list,destination.getParentId());
        }
    }

    @Override
    public void updateInfo(String id, String info) {
        // 查、改、保存
        Destination destination = destinationRepository.findById(id).orElse(null);
        destination.setInfo(info);
        this.update(destination);
    }

    @Override
    public List<Destination> search(String regionId) {
        List<Destination> destinations = null;
        // 1、判断是国内（regionId = -1）还是国外
        if ("-1".equals(regionId)) {
            destinations = destinationRepository.findByParentName("中国");
        }else {
            destinations = this.getDestByRegionId(regionId);
        }

        // 2、查找挂载目的地下的子目的地 设置到 children中；子目的地只要5个
        for (Destination destination : destinations) {
           // List<Destination> childrens  = destinationRepository.findByParentId(destination.getId());
            // childrens.subList(0,5);
            Pageable pageable = PageRequest.of(0,5, Sort.Direction.ASC,"_id");
            List<Destination> childrens  = destinationRepository.findByParentId(destination.getId(),pageable);
            destination.setChildren(childrens);
        }
        return destinations;
    }

    @Override
    public List<StrategyCatalog> getCatalogs(String destId) {
        // 获取所有的分类
        List<StrategyCatalog> strategyCatalogs = strategyCatalogService.findByDestId(destId);
        // 遍历
        for (StrategyCatalog catalog : strategyCatalogs) {
            // 通过catalog id找 攻略
            List<Strategy> strategies = strategyService.findByCatalogId(catalog.getId());
           // 设置到 catalog对象的strategies属性
            catalog.setStrategies(strategies);
        }
        return strategyCatalogs;
    }

    @Override
    public Destination queryByName(String name) {
        return destinationRepository.findByName(name);
    }
}
